// my-fresh-blog/routes/new.tsx
import { h } from "preact";
import { Handlers, PageProps, FreshContext } from "$fresh/server.ts";
import { getDbClient } from "../utils/db.ts";
import HeadComponent from "../components/Head.tsx";
import Container from "../components/Container.tsx";
import Card from "../components/Card.tsx";
import Button from "../components/Button.tsx";

export const handler: Handlers = {
  async GET(_req, ctx: FreshContext) {
    if (!ctx.state.isAdmin) {
      const headers = new Headers();
      const encodedRedirect = encodeURIComponent(new URL(_req.url).pathname);
      headers.set("location", `/admin/login?redirect=${encodedRedirect}`);
      return new Response(null, { status: 303, headers });
    }
    return ctx.render();
  },
  async POST(req, ctx: FreshContext) {
    if (!ctx.state.isAdmin) return new Response("Unauthorized", { status: 403 });
    const form = await req.formData();
    const title = (form.get("title") as string || "").trim();
    const content = (form.get("content") as string || "").trim();
    if (!title || !content) {
      const headers = new Headers();
      headers.set("location", `/new?error=${encodeURIComponent("标题和内容不能为空")}`);
      return new Response(null, { status: 303, headers});
    }
    let client;
    try {
      client = await getDbClient();
      await client.execute("INSERT INTO posts (title, content) VALUES (?, ?)", [title, content]);
    } catch (error) {
      console.error("Error creating post in /new:", error);
      const headers = new Headers();
      headers.set("location", `/new?error=${encodeURIComponent("创建文章失败")}`);
      return new Response(null, { status: 303, headers});
    } finally { if (client) await client.close(); }
    const headers = new Headers();
    headers.set("location", "/?created=true");
    return new Response(null, { status: 303, headers });
  },
};

interface NewPostPageData { error?: string; }

export default function NewPostPage({url}: PageProps<NewPostPageData>) {
  const error = url.searchParams.get("error");
  
  return (
    <>
      <HeadComponent title="写文章" description="创建新的博客文章">
        <link rel="stylesheet" href="/styles.css" />
        <link rel="stylesheet" href="/wangeditor/style.css" />
        <script src="/wangeditor/index.js"></script>
        
        <script dangerouslySetInnerHTML={{
          __html: `
            // 在页面加载完成后初始化编辑器
            document.addEventListener('DOMContentLoaded', () => {
              setTimeout(() => {
                if (typeof window.wangEditor === 'undefined') {
                  console.error('wangEditor未找到，可能脚本加载失败');
                  document.getElementById('editor-container').innerHTML = 
                    '<div class="p-4 text-red-500 text-center">富文本编辑器加载失败，请刷新页面重试</div>';
                  return;
                }
                
                try {
                  const { createEditor, createToolbar } = window.wangEditor;
                  
                  // 简化的编辑器配置，避免使用高级API
                  
                  // 获取编辑器容器和工具栏容器
                  const editorContainer = document.getElementById('editor-container');
                  const toolbarContainer = document.getElementById('toolbar-container');
                  
                  if (!editorContainer || !toolbarContainer) {
                    console.error('编辑器容器未找到');
                    return;
                  }
                  
                  // 创建编辑器 - 简化版
                  const editor = createEditor({
                    selector: editorContainer,
                    html: '',
                    config: {
                      placeholder: '开始写作...',
                      MENU_CONF: {
                        // 图片上传配置
                        uploadImage: {
                          // 基于 base64 编码的 dataUrl 形式上传图片
                          base64LimitSize: 5 * 1024 * 1024, // 限制 5M
                        }
                      }
                    }
                  });
                  
                  // 创建工具栏 - 简化版
                  createToolbar({
                    editor: editor,
                    selector: toolbarContainer,
                    config: {
                      toolbarKeys: [
                        'headerSelect',
                        'bold',
                        'italic',
                        'underline',
                        'through',
                        'fontSize',
                        'fontFamily',
                        'lineHeight',
                        'color',
                        'bgColor',
                        'bulletedList',
                        'numberedList',
                        'justifyLeft',
                        'justifyCenter',
                        'justifyRight',
                        'insertLink',
                        'uploadImage',
                        'insertTable',
                        'codeBlock',
                        'undo',
                        'redo',
                      ]
                    }
                  });
                  
                  // 基本的草稿保存功能
                  const LOCAL_STORAGE_KEY = 'wangeditor-draft-new-post';
                  
                  // 读取草稿
                  const savedContent = localStorage.getItem(LOCAL_STORAGE_KEY);
                  if (savedContent && savedContent !== editor.getHtml()) {
                    if (confirm('检测到有未保存的草稿，是否恢复？')) {
                      editor.setHtml(savedContent);
                    } else {
                      localStorage.removeItem(LOCAL_STORAGE_KEY);
                    }
                  }
                  
                  // 简化的自动保存功能
                  let timer;
                  editor.on('change', () => {
                    // 更新隐藏input
                    document.getElementById('content').value = editor.getHtml();
                    
                    // 计算字数
                    const text = editor.getText();
                    const wordCount = text.replace(/\\s+/g, '').length;
                    const countElem = document.getElementById('word-count');
                    if (countElem) {
                      countElem.textContent = '字数: ' + wordCount;
                    }
                    
                    // 清除之前的定时器
                    clearTimeout(timer);
                    
                    // 自动保存
                    timer = setTimeout(() => {
                      const content = editor.getHtml();
                      if (content && content.length > 10) {
                        localStorage.setItem(LOCAL_STORAGE_KEY, content);
                        
                        const statusElem = document.getElementById('editor-status');
                        if (statusElem) {
                          statusElem.textContent = '草稿已保存 - ' + new Date().toLocaleTimeString();
                          statusElem.style.opacity = '1';
                          setTimeout(() => { statusElem.style.opacity = '0.5'; }, 2000);
                        }
                      }
                    }, 5000);
                  });
                  
                  // 表单提交时清理草稿
                  document.querySelector('form').addEventListener('submit', function() {
                    localStorage.removeItem(LOCAL_STORAGE_KEY);
                  });
                  
                  // 添加清除草稿按钮功能
                  const clearDraftBtn = document.getElementById('clear-draft');
                  if (clearDraftBtn) {
                    clearDraftBtn.addEventListener('click', function() {
                      if (confirm('确定要清除所有草稿吗？')) {
                        localStorage.removeItem(LOCAL_STORAGE_KEY);
                        alert('草稿已清除');
                      }
                    });
                  }
                  
                } catch (error) {
                  console.error('初始化编辑器失败:', error);
                  document.getElementById('editor-container').innerHTML = 
                    '<div class="p-4 text-red-500 text-center">初始化编辑器失败: ' + error.message + '</div>';
                }
              }, 500); // 延迟初始化，确保DOM已完全加载
            });
          `
        }}></script>
      </HeadComponent>
      
      <Container size="md">
        <div class="mb-6 flex justify-between items-center">
          <h1 class="text-2xl font-medium text-mono-100">写文章</h1>
          <Button href="/" variant="ghost" size="sm">返回</Button>
        </div>
        
        {error && (
          <div class="mb-6 px-4 py-3 bg-red-500/10 text-red-400 text-sm rounded">
            {decodeURIComponent(error)}
          </div>
        )}
        
        <Card>
          <form method="POST" class="space-y-5">
            <div>
              <label for="title" class="block mb-1.5 text-sm text-mono-300">
                标题
              </label>
              <input
                type="text"
                name="title"
                id="title"
                required
                placeholder="输入文章标题..."
                class="form-input"
                autocomplete="off"
              />
            </div>
            
            <div>
              <label for="editor-container" class="block mb-1.5 text-sm text-mono-300">
                内容
              </label>
              <div class="rich-text-editor border border-gray-300 rounded-md overflow-hidden">
                <div id="toolbar-container" class="border-b border-gray-300"></div>
                <div id="editor-container" class="p-2" style="height: 400px"></div>
                <div class="flex justify-between items-center px-3 py-2 bg-gray-50 border-t border-gray-300 text-xs text-gray-600">
                  <div id="editor-status" class="opacity-50 transition-opacity">准备就绪</div>
                  <div class="flex space-x-4">
                    <button type="button" id="clear-draft" class="text-blue-600 hover:text-blue-800">清除草稿</button>
                    <span id="word-count">字数: 0</span>
                  </div>
                </div>
              </div>
              <input type="hidden" name="content" id="content" value="" />
            </div>
            
            <div class="pt-4 flex justify-end gap-3">
              <Button href="/" variant="secondary">取消</Button>
              <Button type="submit" variant="primary">发布</Button>
            </div>
          </form>
        </Card>
      </Container>
    </>
  );
}